package com.leetcode.partition2;

import java.util.HashMap;
import java.util.Map;

/**
 * @author `RKC`
 * @date 2021/10/3 9:20
 */
public class LC166分数到小数 {

    public static String fractionToDecimal(int numerator, int denominator) {
        return hashtable(numerator, denominator);
    }

    public static void main(String[] args) {
        System.out.println(fractionToDecimal(1, 96));
//        System.out.println(3 % 7);
    }

    private static String hashtable(long numerator, long denominator) {
        StringBuilder sb = new StringBuilder();
        //如果是负数结果，先加入负号
        if ((numerator > 0 && denominator < 0) || (numerator < 0 && denominator > 0)) sb.append("-");
        numerator = Math.abs(numerator);
        denominator = Math.abs(denominator);
        //小数之前的部分
        sb.append(numerator / denominator);
        if (numerator % denominator == 0) return sb.toString();
        sb.append('.');
        //哈希表记录被除数的下标位置
        Map<Long, Integer> ht = new HashMap<>();
        //分数转小数不会出现无限不循环的小数，因此numerator的值在遇到循环节之前是不会重复的
        while ((numerator = (numerator % denominator) * 10) > 0 && !ht.containsKey(numerator)) {
            ht.put(numerator, sb.length());
            //结果放入
            sb.append(numerator / denominator);
        }
        if (numerator == 0) return sb.toString();
        return sb.insert(ht.get(numerator).intValue(), '(').append(')').toString();
    }
}
